package com.xmhmyh.generalframework.framework.security.handlers;

import com.alibaba.fastjson.JSONObject;
import com.xmhmyh.generalframework.common.entity.Response;
import com.xmhmyh.generalframework.common.enums.ResponseCode;
import com.xmhmyh.generalframework.common.utils.ServletUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 *
 * @author yuyu
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        if(e instanceof InsufficientAuthenticationException){
            ServletUtils.renderString(response,JSONObject.toJSONString(Response.fail(ResponseCode.LOGIN_TIME_OUT)));
        }else if(e instanceof BadCredentialsException){
            ServletUtils.renderString(response,JSONObject.toJSONString(Response.fail(ResponseCode.USERNAME_OR_PASSWORD_ERROR)));
        }else{
            ServletUtils.renderString(response,JSONObject.toJSONString(Response.fail(ResponseCode.LOGIN_FAIL)));
        }
    }
}
